<template>
    <div class='funeral_item_table'>
        <table-edit ref="tableEditss" :dataField="dataField"   :listField="listField"  :data="data"   @input="changeInput" @removeItem="removeItemEvent"></table-edit>
        <div  class='amt_total'>
            <div style='float:left;line-height:40px;display:none'>减免类型：</div>
            <el-select v-model="value" placeholder="请选择" style='width:120px;float:left;display:none'>
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            <div style='float:left;line-height:40px;margin-left:20px;display:none'>总金额优惠：</div>
            <div class='amt_total_item'>
                <span>总金额:&nbsp;&nbsp;</span><span v-text="amt_totals" style='color:green;font-weight:bold;margin-right:30px'></span>
                <span v-if="jm_totals">{{jmTitle}}:&nbsp;&nbsp;</span><span v-text="jm_totals" v-if="jm_totals" style='color:red;font-weight:bold;margin-right:30px'></span>
                <span v-if="bz_totals">补助金额:&nbsp;&nbsp;</span><span v-text="bz_totals" v-if="bz_totals" style='color:red;font-weight:bold;margin-right:30px'></span>
                <span v-if="yh_totals">优惠金额:&nbsp;&nbsp;</span><span v-text="yh_totals" v-if="yh_totals" style='color:red;font-weight:bold;margin-right:30px'></span>
                <span>{{shTitle}}:&nbsp;&nbsp;</span><span v-text="sh_totals" style='font-weight:bold;margin-right:30px'></span>
            </div>
            
        </div>
        <el-tooltip content="点击选择服务项目" placement="top">
            <el-button type="success" icon="el-icon-goods" circle style='position:absolute;bottom:50px;right:50px' @click="drawer=true" ></el-button>
        </el-tooltip>
        <el-drawer
            title="服务项目选择"
            :visible.sync="drawer"
            :direction="direction"
            append-to-body>
            <div class="left_menu">
                <funeral-item-select-show  :sfItemDatas="sfItemData"  :appid="appid" @addItem="addItem" @changeAmt="changeAmts" @removeItem="removeItem" :data="data" :dataField="dataField" :gm_id="gm_id" :type2="extype"></funeral-item-select-show>
            </div>
        </el-drawer>
    </div>
</template>
<script>
import tableEdit  from '../edit/tableEdit.vue'
import FuneralItemSelectShow  from '../byg/FuneralItemSelectShow.vue'
export default {
    props:['dataField','listField','data','params','appid','isgm','extype'],
    name:'funeral-item-table-type',
    components: {
       tableEdit,
       FuneralItemSelectShow
    },
    data(){
        return{
            jmTitle:"减免金额",
            shTitle:"实收金额",
            showtable:false,
            amt_totals:'',
            sh_totals:'',
            yh_totals:"",
            jm_totals:'',
            bz_totals:'',
            sfItemData:[],
            options: [],
            jmJson:[],
            value: '',
            drawer: false,
            direction: 'rtl',
            change:false,
            isJm:false,
            sz_ex42:"",
            gm_id:"",
            yh_totalsOld:"",
            firstTotal:"Y"
        }
    },
    created(){
        
       /* if(this.dataField){
             this.showtable=true;
            this.tableData=this.data[this.dataField];
        }*/
        try{
            if(this.data["gmInfo"])
                this.gm_id=(this.data["gmInfo"].gm_id)
        }catch(e){}
       
        
        try{
           
            if(this.sfItemData.length==0){
                this.$post(this.appid,"byg/funeral/getFuneralSfItem",{gm_id:this.gm_id,type3:escape(this.extype)}).then(data=>{
                    this.sfItemData=[];
                    
                    for(let i=0;i<data.item.length;i++){
                        this.sfItemData.push(data.item[i]);
                    }
                    
                    
                
                })
            }
        }catch(e){}
        this.$parent.$el.getElementsByClassName("el-card__body")[0].style.paddingBottom="0";
        
    },
    mounted(){
        this.changeAmt();
        
    
    },
    computed:{
        dataItem(){
            return this.data[this.dataField];
        }
    },
    methods:{
        removeItemEvent(data){
             /**删除服务项目里的项目 */

            let item=JSON.parse(data);
            
            let id=item.szi_ex8
            let num=0;
            try{
                if(this.data.item&&this.dataField!="item"){
                    let index2=-1;
                    let isDelete2=false;
                    for(let i=0;i<this.data["item"].length;i++){
                        if(this.data["item"][i].szi_ex8==id){
                            console.log("找到了..........................")
                            if(num>0){
                                let datas=this.data["item"][i];
                                let szi_ex2=datas.szi_ex2;
                                let szi_ex5=num*szi_ex2;
                                datas.szi_ex4=num;
                                datas.szi_ex5=szi_ex5;
                                
                                this.$set(this.data["item"],i,datas);
                            }else{
                                index2=i;
                                isDelete2=true;
                            }
                        
                        }
                    }
                  //  alert(isDelete2+"=="+index2)
                    if(isDelete2){
                        this.$delete(this.data["item"],index2);
                    }
                }
            }catch(e){}
        },
        removeItem(data){
            
            let item=JSON.parse(data);
            let id=item.id;
            let num=item.num;

            let isDelete=false;
            let index=-1;
            for(let i=0;i<this.data[this.dataField].length;i++){
                console.log("szi_ex8=="+this.data[this.dataField][i].szi_ex8+"="+id+"="+this.data[this.dataField][i].szi_ex1)
                if(this.data[this.dataField][i].szi_ex8==id){
                    console.log("找到了..........................")
                    if(num>0){
                         let datas=this.data[this.dataField][i];
                        let szi_ex2=datas.szi_ex2;
                        let szi_ex5=num*szi_ex2;
                        datas.szi_ex4=num;
                        datas.szi_ex5=szi_ex5;
                        
                        this.$set(this.data[this.dataField],i,datas);
                    }else{
                       index=i;
                       isDelete=true;
                    }
                   
                }
            }
            if(isDelete){
                 this.$delete(this.data[this.dataField],index);
            }
            /**删除服务项目里的项目 */
            try{
                if(this.data.item&&this.dataField!="item"){
                    let index2=-1;
                    let isDelete2=false;
                    for(let i=0;i<this.data["item"].length;i++){
                        if(this.data["item"][i].szi_ex8==id){
                            console.log("找到了..........................")
                            if(num>0){
                                let datas=this.data["item"][i];
                                let szi_ex2=datas.szi_ex2;
                                let szi_ex5=num*szi_ex2;
                                datas.szi_ex4=num;
                                datas.szi_ex5=szi_ex5;
                                
                                this.$set(this.data["item"],i,datas);
                            }else{
                                index2=i;
                                isDelete2=true;
                            }
                        
                        }
                    }
                    if(isDelete2){
                        this.$delete(this.data["item"],index2);
                    }
                }
            }catch(e){}
        },
        //添加服务项目的主方法
        addItem(data){
            console.log("addItem===========================ss==============");
            console.log(data)
            let datas=JSON.parse(data);
            
            if(datas.addType=="string"){
                let itemType=datas.itemType;
                let name=datas.val;
                
                if(this.sfItemData.length==0){
                    this.$post(this.appid,"byg/funeral/getFuneralSfItem",{gm_id:this.gm_id,type3:escape(this.extype)}).then(data=>{
                        this.sfItemData=[];
                        for(let i=0;i<data.item.length;i++){
                            this.sfItemData.push(data.item[i]);
                        }
                        
                        this.addItemDetail(name,itemType,datas.hour,datas.day);
                    
                    })
                }else{
                    this.addItemDetail(name,itemType,datas.hour,datas.day);
                }
                
            }else{
                if(!datas.szi_ex13)
                    datas.szi_ex13=this.params;
                let isOk=true;
                //相同的项目增加数量
                for(let i=0;i<this.data[this.dataField].length;i++){
                    let szi_ex8=this.data[this.dataField][i].szi_ex8;
                    let szi_ex4=this.data[this.dataField][i].szi_ex4;
                    let szi_ex2=this.data[this.dataField][i].szi_ex2;
                    if(szi_ex8==datas.szi_ex8){
                         szi_ex4++;
                         let data_=this.data[this.dataField][i];
                         data_.szi_ex4=szi_ex4;
                         data_.szi_ex5=szi_ex2*szi_ex4;
                         this.$set(this.data[this.dataField], i , data_); 
                         isOk=false;
                    }
                }
                if(isOk){
                    this.$set(this.data[this.dataField], this.data[this.dataField].length , datas);
                    this.addRelItem(datas,datas.hour,datas.day); 

                    try{
                        if(this.data.item){
                            this.$set(this.data["item"], this.data["item"].length , datas);
                        }
                    }catch(e){}
                }

             
            }
            
            
        },
        changeAmts(){
            this.changeAmt();
        },
        addRelItem(row,hour,day){//添加相搭配项目，并且有些搭配项目是要根据添加或者小时计算数量的，也要更新这些相关联项目的数量
            let sf_id=row.szi_ex8;
            //添加搭配项目
            this.$post(this.appid,"/byg/funeral/getSfItemDp",{sf_id:sf_id}).then(data=>{
              
                
                let szi_ex1_=row.szi_ex1;

                //反向，这个主要是用于添加相搭配项目的时候，找到主项目，并且获取主项目的数量和金额赋值
                //因为这个方法在添加主项目和相关联项目时都会调用
                //比如主服务项目（礼厅）先添加完成，然后找到礼厅相关联的项目szi_ex19,因为礼厅是主项目所有这个字段为空，下面for获取不到row_,就不存在要该礼厅的数量和金额
                //但主项目（礼厅）添加完后，会从后台获取到data.name（在下面）然后添加子项目（冰柜）。子项目添加完成后，又进入该方法，冰柜的szi_ex19值就是相对应的礼厅名称
                //然后就可以反向获取上一步添加好的礼厅的数量，然后冰柜根据获取的数量重新计算金额，赋值给冰柜
                let row_=null;
                for(let i=0;i<this.data[this.dataField].length;i++){
                    let item=this.data[this.dataField][i];
                    let szi_ex2=Number(item.szi_ex2);
                    let szi_ex1=item.szi_ex1;
                    let szi_ex19=item.szi_ex19;
                    
                    if((","+szi_ex19+",").indexOf(","+szi_ex1_+",")!=-1){
                        row_=item;
                    }
                }

                if(row_){
                    let szi_ex4_=Number(row_.szi_ex4);
                    let szi_ex5_=row_.szi_ex5;
                    let szi_ex2=Number(row.szi_ex2);
                    row.szi_ex4=szi_ex4_;
                    row.szi_ex5=szi_ex2*szi_ex4_;
                    //这里其实就是修改刚刚添加的服务项目的数量和金额
                    this.$set(this.data[this.dataField], this.data[this.dataField].length-1 , row); 
                }
                //添加相关联的服务项目
                if(data.name){
                    let names=data.name.split(",");
                    for(let i=0;i<names.length;i++){
                        let n=names[i];
                        //该方法后面还会在调用本方法
                        this.addItemDetail(n,"",hour,day);
                        
                    }
                }
                //找到相关联项目，这个主要是修改相关联项目的数量（根据天数和小时，比如礼厅相关联的项目，冰柜）
                if(data.name2){
                    let names2=data.name2.split(",");
                    
                    for(let h=0;h<names2.length;h++){
                        let n=names2[h];
                        let isSave=false;
                        for(let i=0;i<this.data[this.dataField].length;i++){
                            let item=this.data[this.dataField][i];
                            let szi_ex2=Number(item.szi_ex2);
                            let szi_ex1=item.szi_ex1;
                            let szi_ex4=Number(item.szi_ex4);
                            let szi_ex3=item.szi_ex3;
                            let szi_ex5=Number(item.szi_ex5);
                            let szi_ex5_=0;
                            if(szi_ex1==n){
                                if(szi_ex3.indexOf("时")!=-1){
                                    if(hour){
                                        szi_ex5_=hour*szi_ex2;
                                        item.szi_ex4=hour;
                                        isSave=true;
                                    }
                                    
                                    
                                }else{
                                    if(day){
                                        szi_ex5_=day*szi_ex2;
                                        item.szi_ex4=day;
                                        isSave=true;
                                    }
                                    
                                }
                                if(szi_ex5!=szi_ex5_&&isSave){
                                    item.szi_ex5=szi_ex5_;
                                    this.$set(this.data[this.dataField], i , item); 
                                        
                                }
                            }
                        }
                    }

                    
                }

               // this.setJm();
                //this.changeAmt();
            })
        },
        //根据名字来添加
        addItemDetail(name,itemType,hour,day){
            console.log("name===="+name+"=="+itemType+"=="+hour+"+"+day);
            console.log(this.sfItemData);
             let row=null;
             for(let i=0;i<this.sfItemData.length;i++){
                let szi_ex1=this.sfItemData[i].szi_ex1;
                let szi_ex7=this.sfItemData[i].szi_ex7;
                if(itemType){
                    if(szi_ex1==name&&itemType==szi_ex7){
                        row=this.sfItemData[i];
                    }
                }else{
                    if(szi_ex1==name){
                        row=this.sfItemData[i];
                    }
                }
                
            }
            let isOk=true;
           
             if(row!=null){
                for(let i=0;i<this.data[this.dataField].length;i++){
                    let szi_ex1=this.data[this.dataField][i].szi_ex1;
                    let szi_ex7=this.data[this.dataField][i].szi_ex7;
                    if(itemType){
                        if(szi_ex1==row.szi_ex1&&itemType==szi_ex7){
                            isOk=false;
                        }
                    }else{
                        if(szi_ex1==row.szi_ex1){
                            isOk=false;
                        }
                    }
                    
                }
            
            }
            console.log(row);
            console.log("isOk================="+isOk)
            if(row!=null&&isOk){
                if(itemType){
                    let index=-1;
                    for(let i=0;i<this.data[this.dataField].length;i++){
                        let szi_ex7=this.data[this.dataField][i].szi_ex7;
                        if(szi_ex7==itemType){
                            index=i;
                        }
                    
                    }
                    if(index!=-1){
                        this.$delete(this.data[this.dataField],index)
                        //this.data[this.dataField].splice(index,1);
                       
                    }
                }
                if(!row.szi_ex13)
                    row.szi_ex13=this.params;

                let szi_ex3=row.szi_ex3;
                let sf_ex51=row.szi_ex28
                let num=1;
                let szi_ex2=Number(row.szi_ex2);
                console.log(row)
                if(hour&&szi_ex3.indexOf("时")!=-1){
                    num=hour;
                    let szi_ex5=num*szi_ex2;
                    row.szi_ex5=szi_ex5;
                    row.szi_ex4=num;
                }else if(day&&szi_ex3.indexOf("天")!=-1){
                    if(sf_ex51=="自然天数"){
                        day=Number(day)+1;
                    }
                    day=Number(day)==0 ? 1:day;
                    num=day;
                    let szi_ex5=num*szi_ex2;
                    row.szi_ex5=szi_ex5;
                    row.szi_ex4=num;
                    
                }
                console.log("hour====================="+hour+"===="+day+"=="+szi_ex3);
                console.log(row)

                this.$set(this.data[this.dataField], this.data[this.dataField].length , row); 
                this.addRelItem(row,hour,day)


            }
        },
        changeInput(data){
            console.log("changeInput=====================================")
            
           
          //  this.$emit("input",data);
            let datas=JSON.parse(data);
           
            if(datas.type!="add")
                this.setJm();
            this.changeAmt();
        },
        changeAmt(){
            let amt=0;
            let amt_total=0;
            let amt_jm=0;
            let amt_yh=0;
            this.change=false;
            let amt_bz=0;//补助金额（目前就昆明西郊）
            console.log("changeAmt===================================================333333333333")
            console.log(this.data[this.dataField])
            for(let i=0;i<this.data[this.dataField].length;i++){
                let item=this.data[this.dataField][i];
                let szi_ex2=Number(item.szi_ex2);
                let szi_ex4=Number(item.szi_ex4);
                let szi_ex27=item.szi_ex27;
                let szi_ex5=szi_ex2*szi_ex4;
                let szi_ex5_=item.szi_ex5;
                let szi_ex7_=item.szi_ex7;
                if(szi_ex5!=szi_ex5_){//如果总金额不一样了，才重新赋值
                     item.szi_ex5=szi_ex5;
                     this.$set(this.data[this.dataField], i , item); 
                     this.change=true;
                }
               
                
                if(szi_ex5<0)
                    amt_jm+=szi_ex5;
                
                else
                    amt_total+=szi_ex5;
                
                if(szi_ex7_.indexOf("补助")!=-1){
                    amt_bz+=szi_ex5;
                }else{
                    amt+=szi_ex5;
                }
                if(szi_ex27){
                    szi_ex27=Number(szi_ex27);
                    amt-=szi_ex27;
                    amt_yh+=szi_ex27;
                }
                console.log("szi_ex7+++==========="+szi_ex7_)
               
            }
            
            this.amt_totals=amt_total;
            this.jm_totals=-amt_jm;
            this.bz_totals=amt_bz;
            this.sh_totals=amt;
            this.yh_totals=amt_yh;
            if(this.bz_totals){
                this.shTitle="自费金额";
            }
            if(this.firstTotal=="Y"){
                this.yh_totalsOld=this.yh_totals;
                this.firstTotal="N";
            }
            if(this.yh_totals!=this.yh_totalsOld){
                try{
                    this.data["szInfo"].sz_ex59="待审核";
                    this.data["szInfo"].sz_dat12=this.getNowDate();

                    this.data["commonAuth"]={
                        ca_ex6:"待审核",
                        ca_dat1:this.getNowDate()
                    };
                }catch(e){}
            }
            console.log("this.bzTotal========"+amt_bz)
        },
        getDaysBetween(dateString1,dateString2){
            var  startDate = Date.parse(dateString1);
            var  endDate = Date.parse(dateString2);
            var days=(endDate - startDate)/(1*24*60*60*1000);
            // alert(days);
            return  days;
        },
        getDaysBetweenHour(dateString1,dateString2){
            var  startDate = Date.parse(dateString1);
            var  endDate = Date.parse(dateString2);
            var days=(endDate - startDate)/(1*60*60*1000);
            // alert(days);
            return  days;
        },
        
         loadMeal(sId){
            
              return new Promise((resolve,reject) => {
               
                this.$postAsync("bygex","/byg/funeral/getFuneralSfMealItem",{sId:sId}).then(data=>{
                    console.log("loadMEAL==============================");
                    resolve(data);
                });
              });
             
           
           
        },
       
            //startDateStr(2017-02-22) endDateStr(2018-02-21)
        getDateYearSub(startDateStr, endDateStr) {
            var day = 24 * 60 * 60 *1000; 

            var sDate = new Date(Date.parse(startDateStr.replace(/-/g, "/")));
            var eDate = new Date(Date.parse(endDateStr.replace(/-/g, "/")));

            //得到前一天(算头不算尾)
            sDate = new Date(sDate.getTime() - day);

            //获得各自的年、月、日
            var sY  = sDate.getFullYear();     
            var sM  = sDate.getMonth()+1;
            var sD  = sDate.getDate();
            var eY  = eDate.getFullYear();
            var eM  = eDate.getMonth()+1;
            var eD  = eDate.getDate();
            console.log(eY+"="+sY+"="+sM+"="+eM)
            if(eY > sY && sM == eM) {
                return eY - sY;
            } else {
                alert("两个日期之间并非整年，请重新选择");
                return 0;
            }
        },
        getNowDate(){
            var mydate=new Date();
            var mymonth=mydate.getMonth()+1;
            var myday= mydate.getDate();
            var year= mydate.getFullYear();
            if(mymonth<10)
                mymonth="0"+mymonth;
            if(myday<10)
                myday="0"+myday;
            var date = year+"-"+mymonth+"-"+myday
            return date;
        }
        
    },
    watch:{
       
         data:{
            handler: function (newVal) {
                let datas=this.$refs.tableEditss.getData();
                console.log("变更了--------------------------------------------------------")
                console.log(this.data);
                
            },      
            deep: true    //深度监听
        },
        dataItem:{
            deep:true,
            handler:function(newV,oldV){
                
                this.changeAmt();
                
                
            }
        }
    }
     
}
</script>
<style scoped>
.funeral_item_table{
    height:100%;
    display:flex;
    flex-direction: column;
    overflow:hidden;
    position:relative;
}
.tableEdit{
    flex:1;
}
.amt_total{
    height:40px;
    border:1px solid #ddd;
    line-height:20px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    text-align: right;
    background:#ddd;
    -moz-box-shadow: 2px 2px 10px #909090;
   -webkit-box-shadow: 2px 2px 10px #909090;
   box-shadow:2px 2px 10px #909090;

}
.amt_total_item{
    
    padding:10px;
}
.funeral_item_table >>> .el-drawer{
    width:65% !important;
}
.amt_total >>> .el-input__inner{
    height:35px;
}
</style>
<style >

.el-drawer__header{
    margin-bottom:0 !important;
    padding:10px 10px 0 !important;
}
.el-card__header{
    padding:5px 5px !important;
}
.el-card__body{
    padding-top:0 !important;
    padding-left:0 !important;
    padding-right:0 !important;
}
</style>
<style >

</style>